
package com.cnpinxi.service;


import com.alipay.config.AlipayConfig;
import com.alipay.util.AlipaySubmit;
import com.cnpinxi.dao.AliNorificationMapper;
import com.cnpinxi.domain.AliNorification;
import com.cnpinxi.domain.Order;
import com.cnpinxi.domain.PayParameter;
import com.cnpinxi.domain.Payment;
import com.cnpinxi.myRunTime.MyRunTimeExcption;
import com.cnpinxi.tool.PropertyUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * Created by Baggio on 2017/2/16.
 */
@Service("aliPayService")
public class AliPayServiceImpl extends com.cnpinxi.service.PayBase implements PayService {
    @Autowired
    private AliNorificationMapper aliNorificationMapper;

    @Autowired
    private OrderService orderService;
    /**
     * 支付宝提供给商户的服务接入网关URL(新)
     */
    private static final   String PAYURL = PropertyUtils.getValue("ali.pay_url");
    /**
     * WAIT_BUYER_PAY	交易创建，等待买家付款
     TRADE_CLOSED	未付款交易超时关闭，或支付完成后全额退款
     TRADE_SUCCESS	交易支付成功
     TRADE_FINISHED	交易结束，不可退款
     */
    private static final String ORDER_STAUS_TRADE_SUCCESS = "TRADE_SUCCESS";
    private static final String ORDER_STAUS_TRADE_FINISHED = "TRADE_FINISHED";
    @Override
    public PayParameter pay(String orderId, String price, String remoteAddr, Map<String,String> payParametersMap) {
        logger.info("AliPayServiceImpl===>>>>");
if (StringUtils.isBlank(orderId)){
    throw  new MyRunTimeExcption("订单号不存在，支付失败！");
}
        String out_trade_no = orderId;


        String subject=this.getProductName(orderId);
        logger.info("subject====>>>"+subject+"price===>"+price);
        //付款金额，必填
        //String total_fee =  price;
        DecimalFormat decimalFormat=new DecimalFormat("0.00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
        String total_fee=decimalFormat.format(new BigDecimal(price).divide(new BigDecimal(100)));//format 返回的是字符串
        //商品描述，可空
        String body = "";

        PayParameter payParameter = new PayParameter();
        payParameter.setBankUrl(PAYURL);


        //把请求参数打包成数组
        Map<String, String> sParaTemp = new HashMap<String, String>();
        sParaTemp.put("service", AlipayConfig.service);
        sParaTemp.put("partner", AlipayConfig.partner);
        sParaTemp.put("seller_id", AlipayConfig.seller_id);
        sParaTemp.put("_input_charset", AlipayConfig.input_charset);
        sParaTemp.put("payment_type", AlipayConfig.payment_type);
        sParaTemp.put("notify_url", AlipayConfig.notify_url);
        sParaTemp.put("return_url", AlipayConfig.return_url);
        sParaTemp.put("anti_phishing_key", AlipayConfig.anti_phishing_key);
        sParaTemp.put("exter_invoke_ip", AlipayConfig.exter_invoke_ip);
        sParaTemp.put("out_trade_no", out_trade_no);
        sParaTemp.put("subject", subject);
        sParaTemp.put("total_fee", total_fee);
        sParaTemp.put("body", body);
        //其他业务参数根据在线开发文档，添加参数.文档地址:https://doc.open.alipay.com/doc2/detail.htm?spm=a219a.7629140.0.0.O9yorI&treeId=62&articleId=103740&docType=1
        //如sParaTemp.put("参数名","参数值");
        Map<String, String> map=  AlipaySubmit.buildRequestPara(sParaTemp);
        System.out.println(map);
        payParameter.setMap(map);
        //建立请求
//        String sHtmlText = AlipaySubmit.buildRequest(sParaTemp,"get","确认");
//        out.println(sHtmlText);
        payParameter.setPayStatus(PayParameter.PAY_STATUS_UNPAYED);
        payParameter.setPayMode(Payment.PAY_MODE_ALIPAY);
        return payParameter;
    }

    @Override
    public Map<String, String> notification(Map<String, String> map) {
       /* if (AlipayNotify.verify(map)==false){
            logger.info("【支付宝回调：】验签失败！"+map.toString());
            throw  new MyRunTimeExcption("支付失败！");
        }*/
        String orderStatus=map.get("trade_status");
        if (StringUtils.isBlank(orderStatus)){
            throw  new MyRunTimeExcption("trade_status is null");
        }
        String orderId=map.get("out_trade_no");
        if (StringUtils.isBlank(orderId)){
            throw  new MyRunTimeExcption("orderId is null");
        }
        String acqSeqId=map.get("trade_no");
        if (StringUtils.isBlank(acqSeqId)){
            throw  new MyRunTimeExcption("acqSeqId is null");
        }

        Order order = orderService.getOrderById(Long.parseLong(orderId));
        if(order==null){
            throw new MyRunTimeExcption("order Is null");
        }

        AliNorification aliNorification=aliNorificationMapper.selectAliNorification(map);
        if (aliNorification==null){
            logger.info("Ali第一次回调，需要处理！===》》"+acqSeqId);
            aliNorification=new AliNorification();

        aliNorification.setNotifyTime(map.get("notify_time"));
        aliNorification.setNotifyType(map.get("notify_type"));
        aliNorification.setNotifyId(map.get("notify_id"));
        aliNorification.setAppId(map.get("app_id"));
        aliNorification.setCharset(map.get("charset"));
        aliNorification.setVersion(map.get("version"));
        aliNorification.setSignType(map.get("sign_type"));
        aliNorification.setSign(map.get("sign"));
        aliNorification.setTradeNo(map.get("trade_no"));
        aliNorification.setOutTradeNo(map.get("out_trade_no"));
        aliNorification.setOutBizNo(map.get("out_biz_no"));
        aliNorification.setBuyerId(map.get("buyer_id"));
        aliNorification.setBuyerLogonId(map.get("buyer_logon_id"));
        aliNorification.setSellerId(map.get("seller_id"));
        aliNorification.setSellerEmail(map.get("seller_email"));
        aliNorification.setTradeStatus(map.get("trade_status"));
        aliNorification.setTotalAmount(map.get("total_amount"));
        aliNorification.setReceiptAmount(map.get("receipt_amount"));
        aliNorification.setInvoiceAmount(map.get("invoice_amount"));
        aliNorification.setBuyerPayAmount(map.get("buyer_pay_amount"));
        aliNorification.setPointAmount(map.get("point_amount"));
        aliNorification.setRefundFee(map.get("refund_fee"));
        aliNorification.setSubject(map.get("subject"));
        aliNorification.setBody(map.get("body"));
        aliNorification.setGmtCreate(map.get("gmt_create"));
        aliNorification.setGmtPayment(map.get("gmt_payment"));
        aliNorification.setGmtRefund(map.get("gmt_refund"));
        aliNorification.setGmtClose(map.get("gmt_close"));
        aliNorification.setFundBillList(map.get("fund_bill_list"));
        aliNorification.setPassbackParams(map.get("passback_params"));
        aliNorification.setVoucherDetailList(map.get("voucher_detail_list"));
            aliNorification.setCreateTime(new Date());
            logger.info(acqSeqId+"写入记录=====>>>>>"+order.getOrderId());
        aliNorificationMapper.insertAliNorification(aliNorification);
logger.info("orderStatus=====>>>>>"+orderStatus);
        if (orderStatus.equals(ORDER_STAUS_TRADE_SUCCESS)) {

            super.payin(Long.parseLong(orderId), acqSeqId);
        } else {
            logger.info("payRollBack=====>>>>>"+orderStatus);
          //TODO 支付失败

        }
        }
        else
        {
            logger.info("Ali非第一次回调，已经处理过了，不需要再处理！===》》"+acqSeqId);
        }
return null;
    }

    @Override
    public PayParameter refund(Order order, Integer price) {
        return null;
    }

    public static void main(String[] args) {
        String price="1";
        DecimalFormat decimalFormat=new DecimalFormat("0.00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
        String total_fee=decimalFormat.format(new BigDecimal(price).divide(new BigDecimal(100)));//format 返回的是字符串
        System.out.println("=====>>"+total_fee);
    }
}